package com.pz.cloud.framework.deptUser.model;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.pz.cloud.framework.base.expection.CustomRuntimeException;
import com.pz.cloud.framework.business.leagueMem.entity.LeagueMem;
import com.pz.cloud.framework.business.leagueMem.service.ILeagueMemService;
import com.pz.cloud.framework.util.BeanUpdateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.model.BaseImportModel;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 部门成员导入
 * @author mzz
 */
@Component
@Slf4j
public class DeptUserImportModel extends BaseImportModel<SysUserDepart> {

    @Autowired
    private ISysUserDepartService userDepartService;
    @Autowired
    private ISysDepartService departService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 获取导入模板文件
     * @return
     */
    @Override
    protected  String getTemplateFilePath(){
        String path = "excelTemplate/import/deptUser.xlsx";
        return path;
    }

    @Override
    protected ImportValidetor validateEmptyField() {
        return ImportValidetor.instanec().addValidate("username", "学工号")
                .addValidate("orgCode", "部门编码");
    }

    /**
     * 保存导入的数据
     */
    @Override
    public void saveData(SysUserDepart data){
        String username = data.getUsername();
        SysUser sysUser = sysUserService.getUserByName(username.trim());
        if(sysUser==null){
            throw new CustomRuntimeException("学工号【"+username+"】不存在！");
        }

        List<SysDepart> sysDeparts = departService.queryDepartsByOrgCode(data.getOrgCode());
        if (CollectionUtils.isEmpty(sysDeparts)) {
            throw new CustomRuntimeException("部门不存在：" + data.getOrgCode());
        }

        List<SysUser> sysUsers = userDepartService.queryUserByDepId(sysDeparts.get(0).getId());
        if (CollectionUtils.isNotEmpty(sysUsers)) {
            for (SysUser user : sysUsers) {
                if (user.getId().equals(sysUser.getId())) {
                    log.info("学工号" + data.getUsername() + "已存在部门" + data.getOrgCode() + "中");
                    return;
                }
            }
        }
        data.setUserId(sysUser.getId());
        data.setDepId(sysDeparts.get(0).getId());
        userDepartService.save(data);
    }


    /**
     * 导入模板名称
     * @return
     */
    @Override
    public String getDemoFileName(){
        return "部门成员导入模板";
    }

}
